<?php
namespace app\index\controller;


use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

//商品入库
class Rk extends Controller{
	
	//获取商品列表
	public function index(){
		
		$req = Request::instance();
		
		if($req->isPost()){
			//提交入库
			if(!Session::has('agent_id')){
				ajax('请先登陆');
			}
			defined('AGENT_ID') or define('AGENT_ID',Session::get('agent_id'));
			
			$param = ['agentid' => AGENT_ID];
			$pm = [
				'agentid' => AGENT_ID,
				'productid' => $req->param('productid',0,'intval'),
				'zscode' => $req->param('zscode')
			];
			if($pm['productid'] < 1){
				ajax('请选择正确的商品');
			}
			if(!preg_match('/^\d+(;\d+)*$/',$pm['zscode'])){
				ajax('追溯码错误');
			}
			$response = \ServerHelper::post('^/fw/productrk',$pm);
			$data = $this->J($response);
			if(empty($data['flag'])){
				ajax($data['msg']);
			}
			ajax($data['msg'],true);
		}
		
		if(!IS_TEST){
			if(!Session::has('agent_id')){
				//$this->wxlogin(); //方式①：微信登陆
				$this->redirect('Rk/login'); //方式②：账号密码登陆
				exit();
			}
		}else{
			Session::set('agent_id',TEST_AGENT_ID);
		}
		
		defined('AGENT_ID') or define('AGENT_ID',Session::get('agent_id'));
		$param = ['agentid' => AGENT_ID];
		$response = \ServerHelper::post('^/fw/productlist',$param);
		$data = $this->J($response);
		
		//微信配置
		$response = \ServerHelper::post('GetWeChatConfig');
		$response = json_decode($response,true);
		if(empty($response['appid'])){
			return view('public/error_show',['msg'=>'数据错误']);
		}
		$hp = new \WechatBase($response['appid'],$response['appsecret']);
		$param = $hp->getSignPackage();
		$data['wx'] = $param;
		return view('',$data);
	}
	
	//登陆方式2：账号密码登陆
	public function login(){
		$req = Request::instance();
		if($req->isPost()){
			$pm = [
				'userid' => $req->param('user'),
				'pwd' => $req->param('pwd'),
			];
			if($pm['userid'] == ''){ ajax('请输入登陆账号'); }
			if($pm['pwd'] == ''){ ajax('请输入登陆密码'); }
			
			$res = \ServerHelper::post('^/manager/userlogin',$pm);
			$data = $this->J($res);
			if(empty($data['flag'])){
				ajax($data['msg']);
			}
			Session::set('agent_id',$data['data']);
			ajax('登陆成功',true);
		}
		return view();
	}
	
	public function test(){
		return view('public/error_show', [
			'msg'  => '请在微信中登陆',
		]);
	}
	
	public function wxlogin(){
		if(!__iswechat()){
			__log('入库登录：不是在微信里登陆','weixin');
			return view('public/error_show', [
				'msg'  => '请在微信中登陆',
			]);
			exit();
		}
		
		$cfg = \ServerHelper::GetWeChatConfig();
		if(!isset($cfg['appid'])){
			__log('入库登录：没有设置微信appid','weixin');
			return view('public/error_show',['msg'=>'系统错误']);
			exit();
		}
		
		$appid = $cfg['appid'];
		
		$request = Request::instance();
		
		$redirect_uri = urlencode($request->domain() . url('Rk/wechat_redirect'));
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize";
		$url.="?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		
		$this->redirect($url);
	}
	
	public function wechat_redirect(){
		//载入配置信息
		$cfg = \ServerHelper::GetWeChatConfig();
		if(
			!isset($cfg['appid']) || 
			!isset($cfg['appsecret'])
			){
			__log('入库登录：没有设置微信appid或appsecret','weixin');
			return view('public/error_show',['msg'=>'系统错误']);
			exit();
		}
		$appid = $cfg['appid'];
		$appsecret = $cfg['appsecret'];
		
		//拉取请求
		$request = Request::instance();

		//第一步返回的 得到了 Code
		$code = $request->param('code','');
		if($code == ''){
			return view('public/error_show',['msg'=>'登陆发起失败']);
		}

		//第二步：通过code换取网页授权access_token
		$url ="https://api.weixin.qq.com/sns/oauth2/access_token";
		$url.="?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$info = $this->getJson($url);
		if(!isset($info['refresh_token'])){
			return view('public/error_show',['msg'=>'登陆发起失败']);
		}

		//第三步：刷新access_token（如果需要）
		$refresh_token = $info['refresh_token'];
		$url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
		$url.= "?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
		$info = $this->getJson($url);
		if(
			!isset($info['access_token']) || 
			!isset($info['openid'])
		){
			return view('public/error_show',['msg'=>'登陆发起失败']);
		}
		
		__log('入库登陆：' . json_encode($info) , 'weixin');
		
		//通过
		$pm = [
			'wechatid' => $info['openid']
		];
		$res = \ServerHelper::post('^/agent/getagentid',$pm);
		$data = $this->J($res);
		if(empty($data['flag'])){
			return view('public/error_show',['msg'=>$data['msg']]);
		}
		
		Session::set('agent_id',$data['data']);
		$this->redirect('Rk/index');
	}
	
	
	private function J($list){
		$data = json_decode($list,true);
		if(!isset($data['flag'])){
			if(Request::instance()->isAjax()){
				ajax('网络错误');
			}
			exit('net error');
		}
		return $data;
	}
	
	private function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}
	
}


